package com.yzc.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzc.Authentication.JwtAuthenticationToken;
import com.yzc.execption.ZcException;
import com.yzc.mapper.TicketFlightOrderMapper;
import com.yzc.mapper.TicketMainOrderMapper;
import com.yzc.model.DTO.FlightOrderDetail;
import com.yzc.model.entity.ticket_order.OrderFlight;
import com.yzc.model.entity.ticket_order.OrderMain;
import com.yzc.model.vo.page.PageResult;
import com.yzc.model.vo.ticket_order.FlightOrderVo;
import com.yzc.result.Result;
import com.yzc.result.ResultCodeEnum;
import com.yzc.service.TicketFlightOrderService;
import com.yzc.snow.SnowflakeIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.yzc.model.entity.ticket_order.OrderMain.PayMethod.*;
import static com.yzc.rabbit.OrderStatus.status_UNPAID;
import static com.yzc.rabbit.OrderType.FLIGHT;

@Slf4j
@Service
public class TicketFlightOrderServiceImpl extends ServiceImpl<TicketFlightOrderMapper, OrderFlight>
        implements TicketFlightOrderService {

    @Autowired
    private TicketFlightOrderMapper mapper;

    @Autowired
    private TicketMainOrderMapper mainOrderMapper;


    private final SnowflakeIdUtil snowflakeIdUtil;
    private final PaymentServiceImpl paymentService;


    public TicketFlightOrderServiceImpl(SnowflakeIdUtil snowflakeIdUtil, PaymentServiceImpl paymentService) {
        this.snowflakeIdUtil = snowflakeIdUtil;
        this.paymentService = paymentService;
    }

    private void setMachineId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof JwtAuthenticationToken) {
            JwtAuthenticationToken jwtAuthentication = (JwtAuthenticationToken) authentication;
            snowflakeIdUtil.setMachineId(Long.parseLong(jwtAuthentication.getUserId()));
        } else {
            snowflakeIdUtil.setMachineId(1); // 默认值
        }
    }


    @Override
    @Transactional
    public void createTicketOrder(FlightOrderDetail flight) {

        // 设置 machineId
        setMachineId();

        // 生成订单ID
        long orderId = snowflakeIdUtil.nextId();

        // 创建主订单
        OrderMain mainOrder = new OrderMain();
        mainOrder.setOrderId(orderId);
        mainOrder.setUserId(flight.getUserId());
        mainOrder.setOrderType(FLIGHT.getCode());
        mainOrder.setTotalAmount(flight.getTotalAmount());
        mainOrder.setOrderStatus(status_UNPAID.getCode()); // 1 表示待支付
        mainOrder.setCreateTime(new Date());

        mainOrderMapper.insertOrderMain(mainOrder);

        // 创建景点订单
        mapper.createTicketOrder(flight, orderId);

        log.info("订单创建成功，订单ID: {}", orderId);
    }

    @Override
    public PageResult<FlightOrderVo> listOrders(Long userId, Integer pageNo, Integer pageSize) {
        if (pageNo < 1 || pageSize < 1) {
            throw new IllegalArgumentException("分页参数必须大于0");
        }

        int offset = (pageNo - 1) * pageSize;

        try {
            // 执行查询
            List<FlightOrderVo> orders = mainOrderMapper.findFlightOrdersByUserId(userId, pageSize, offset);

            // 获取总记录数
            Long total = mainOrderMapper.countFlightOrders(userId);

            // 封装分页结果
            PageResult<FlightOrderVo> result = new PageResult<>();
            result.setPageNo(pageNo);
            result.setPageSize(pageSize);
            result.setTotal(total);
            result.setData(orders);

            log.info("查询订单列表成功，用户ID: {}", userId);
            return result;
        } catch (Exception e) {
            log.error("查询订单列表失败，用户ID: {}", userId, e);
            throw new RuntimeException("查询订单列表失败", e);
        }
    }

    @Override
    @Transactional
    public Result<String> payOrder(Long orderId, String paymentMethod) {
        try {
            String method = null;

            // 根据支付方式设置 method
            if (Objects.equals(paymentMethod, WECHAT_PAY.getDisplayName())) {
                method = WECHAT_PAY.getDisplayName();
            } else if (Objects.equals(paymentMethod, ALIPAY.getDisplayName())) {
                method = ALIPAY.getDisplayName();
            } else if (Objects.equals(paymentMethod, BANK_CARD.getDisplayName())) {
                method = BANK_CARD.getDisplayName();
            } else if (paymentMethod != null) {
                method = OTHER.getDisplayName();
            } else {
                return Result.fail(ResultCodeEnum.FAIL.getCode(), "支付方式不能为空");
            }

            // 调用支付服务
            paymentService.payOrder(orderId, method);
            return Result.success("支付成功");
        } catch (ZcException zcException) {
            return Result.fail(ResultCodeEnum.FAIL.getCode(), "支付失败");
        }
    }


}
